package com.gblfy.lyrabbitmq.returns;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * 消息 return机制
 * 路由失败的消息会先走这，然后到ConfirmCallBackListener记录异常错误信息
 *
 * @author gblfy
 * @Date 2021-09-28 9:59
 */
@Component("returnCallBackListener")
public class ReturnCallBackListener implements RabbitTemplate.ReturnCallback {

    //打印日志 实时定位
    private final static Logger log = LoggerFactory.getLogger(ReturnCallBackListener.class);

    /**
     * 消息无法路由 触发消息 return机制
     * <p>
     * 1. 消费者在消息没有被路由到合适队列情况下会被return监听，而不会自动删除
     * 2. 会监听到生产者发送消息的关键信息
     * 3. 根据关键信息，后续进行补偿机制，做消息补发处理
     * </p>
     *
     * @param message    消息实体
     * @param replyCode  应答码312
     * @param replyText  NO_ROUTE
     * @param exchange   交换机
     * @param routingKey 路由routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

        log.info("DeliveryTag: {}", message.getMessageProperties().getDeliveryTag());
        log.info("ContentType: {}", message.getMessageProperties().getContentType());
        log.info("ContentEncoding: {}", message.getMessageProperties().getContentEncoding());

        log.info("消息发送的指定交换机: {}", exchange);
        log.info("队列路由的routingKey: {}", routingKey);
        log.info("队列的响应码replyCode: {}", replyCode);
        log.info("队列的响应信息: {}", replyText);
        //TODO 消息发送交换机成功 路由失败 保存轨迹记录
    }
}
/**
 * 场景结果示例：
 * return exchange: FIS-TRACE-COMMON-EXCHANGE, routingKey: fis-str.user, replyCode: 312, replyText: NO_ROUTE
 * correlationData: CorrelationData [id=30d924db-77b4-41df-bbe6-9a8f0eb3fe7a]
 * ack: true
 * 消息: CorrelationData [id=30d924db-77b4-41df-bbe6-9a8f0eb3fe7a]，已经被ack成功
 */

